import { AfterViewInit, ChangeDetectorRef, Component, Input, OnInit, ViewChild } from '@angular/core';
import { SFComponent, SFSchema } from '@delon/form';
import { ApiService } from '@core/services/api';
import { HttpClient } from '@angular/common/http';
import { NzMessageService, NzModalRef } from 'ng-zorro-antd';
import { UtilService } from '@core/services/util.service';

@Component({
  selector: 'app-user-edit',
  templateUrl: './user-edit.component.html',
  styles: []
})
export class UserEditComponent implements OnInit,AfterViewInit {
  @ViewChild('sf', { static: false }) sf: SFComponent;
  @Input()type: 0 | 1;
  @Input()
  set _param(value) {
    if (!value) return;
    this.flag=false;
    this.getDepts()
    this.param = value;
    this.getUserInfo(this.param.userAccount).then(res => {
      console.log(res)
      // this.param.dept = res.data.depts.map(item => item.id);
      this.param.role = res.data.roles.map(item => item.id);
    });
    setTimeout(()=>{
      if(!value.state){ 
        return
      }
      this.getAreaTreeNode(value.state).then((res)=>{
        let arr=res.map(item =>{
          return {label:item.title,value:item.key}
        })
        if(this.util.getStorage('userAccount') != '"admin"'){
          arr=arr.filter(item => item.value == this.city);
        }
        const statusProperty = this.sf.getProperty('/city')!;
        statusProperty.schema.enum=arr;
        statusProperty.widget.reset('');
      });

      this.getTree(value.city).then((res)=>{
        let arr=this.transformTree(res);
        let list=[];
        let arr2=[];
        for(let item of this.cities){
          let arr3=this.sonsTree(arr,item.cityId,[]);
          arr2=[...arr2,...arr3];
        }
        if(this.util.getStorage("userAccount") == '"admin"'){
          list=arr;
        }else{
          list=arr2;
        }
        const statusProperty = this.sf.getProperty('/cityId')!;
        statusProperty.schema.enum=list;
        statusProperty.widget.reset('');
      });
    },200)
    if(value.cityStr){
      const cityStr = value.cityStr.split(",")
      this.param.cityId = cityStr
    }
  };
  flag:boolean = true;
  city:any;
  province:any;
  cities:any;
  param: any;
  showForm = false;
  isPartner:boolean = false
  schema: SFSchema = {
    properties: {
      userName: {
        type: 'string',
        title: '姓名',

      },
      userAccount: {
        type: 'string',
        title: '账号'
      },
      role: {
        type: 'string',
        title: '角色',
        enum: [],
        ui: {
          widget: 'select',
          mode: 'multiple',
          dropdownStyle: {
            'max-height': '300px'
          }
        }
      },
      state: {
        type: 'string',
        title: '省',
        enum:[],
        ui:{
          widget: 'select',
          change: (value, orgData) => {
            this.getAreaTreeNode(value).then((res)=>{
              let arr=res.map(item =>{
                return {label:item.title,value:item.key}
              })
              if(this.util.getStorage('userAccount') != '"admin"'){
                arr=arr.filter(item => item.value == this.city);
              }
              const statusProperty = this.sf.getProperty('/city')!;
              statusProperty.schema.enum=arr;
              statusProperty.widget.reset('');
            });
          },
        }
      },
      city: {
        type: 'string',
        title: '市',
        enum:[],
        ui:{
          widget: 'select',
          change: (value, orgData) => {
            this.getTree(value).then((res)=>{
              let arr=this.transformTree(res);
              let arr2=[];
              let list=[];
              for(let item of this.cities){
                let arr3=this.sonsTree(arr,item.cityId,[]);
                arr2=[...arr2,...arr3];
              }
              if(this.util.getStorage("userAccount") == '"admin"'){
                list=arr;
              }else{
                list=arr2;
              }
              const statusProperty = this.sf.getProperty('/cityId')!;
              statusProperty.schema.enum=list;
              statusProperty.widget.reset('');
            });
          },
        }
      },
      cityId: {
        type: 'string',
        title: '权限区域',
        enum: [],
        ui: {
          widget: 'tree-select',
          checkable: true,
          multiple: true,
          hideUnMatched:true,
          checkStrictly:true,
          dropdownStyle: {
            'max-height': '300px'
          }
        }
      },
      userType:{
        type:"string",
        title:"用户类型",
        enum:[
          {label:"管理员",value:"1"},
          {label:"普通用户",value:"0"}
        ],
        ui:{
          widget:'select'
        }
      },
      // status: {
      //   type: 'string',
      //   title: '数据状态',
      //   enum: [
      //     {label: '启用', value: true},
      //     {label: '停用', value: false},
      //   ],
      //   ui: {
      //     widget: 'select'
      //   }
      // },
      userRemark: {
        type: 'string',
        title: '备注'
      }

    },
    required: ['userName','userType', 'userAccount','role','state','city','cityId']
  }
  getRoleList(): Promise<any>{
      return this.http.request<any>(this.api.role.list.method, this.api.role.list.url, {body: {status: 1}}).toPromise();
  }
  getPermitions(): Promise<any> {
    return this.http.request<any>(this.api.permision.list.method, this.api.permision.list.url, {body: {status: 1}}).toPromise();
  }
  getUserInfo(account: string): Promise<any>{
    return this.http.request<any>(this.api.user.detail.method, this.api.user.detail.url, {body: {userAccount: account}}).toPromise();
  }
  formSubmit(data) {
    const userNow = JSON.parse(this.util.getStorage("userNow"))
    const body: any = {
      userName: data.userName,
      userAccount: data.userAccount,
      status: true,
      userRemark: data.userRemark,
      id: data.id,
      userType:data.userType,
      createBy:userNow.userAccount
    };
    if(this.isPartner){//是加盟商
      body.userType = 0
    }
    if (this.type === 0) {
      body.userPassword = '123456';
    }
    body.roles = data.role.map(item => {
      return {id: item};
    })
    // body.depts = data.dept.map(item => {
    //   return {id: item}
    // })
    let arr=[]
    for(let item of data.cityId){
      arr.push({
        "state":data.state,
        "city":data.city,
        "cityId":item
      })
    }
    body.userCities = arr
    const url = this.type === 0 ? this.api.user.add.url : this.api.user.update.url;
    const method = this.type === 0 ? this.api.user.add.method : this.api.user.update.method
    this.http.request<any>(method, url,  { body}).subscribe(res => {
      console.log(res)
      if (res.status === '200' || res.status === '201') {
        this.msg.success('操作成功');
        this.modalRef.triggerOk();
      } else {
        this.msg.error(res.message)
      }
    })

  }

  //获取省，市
  getAreaTreeNode(id): Promise<any> {
    return new Promise<any>((resolve, reject) => {
      this.http.post(this.api.city.tree.url, {id}).subscribe((res:any) => {
        console.log(res);
        if (res.data && res.data.length > 0) {
          const node = res.data.map(item => {
            return {
              key: item.id,
              title: item.name,
              level: item.cityRank,
              rank: Number(item.rank),
              parentAllId: item.parentAllId,
              parentId:item.parentId
            }
          })
          resolve(node);

        } else {
          resolve([])
        }
      })
    })
  }
  //获取市下面的区，街道，小区
  getTree(id):Promise<any>{
    const self = this
    return new Promise<any>((resolve, reject) => {
      this.http.post(this.api.city.allTree.url, {id}).subscribe((res:any) => {
        if (res.data && res.data.length > 0) {
          let node = res.data.map(item => {
            return {
              key: item.id,
              title: item.name,
              rank: Number(item.rank),
              // parentAllId: item.parentAllId,
              // parentId:item.parentId,
              pId:item.parentId,
              id:item.id
            }
          })
          node=node.filter(item => item.rank < 9);
          if(self.isPartner){// 是加盟商
            node = node.filter(item => item.rank < 5)
          }
          resolve(node);
        } else {
          resolve([])
        }
      })
    })
  }
  //找到某一父节点下的所有子节点
  sonsTree(arr, id,temp) {
    for(let item of arr){
      if(item.id == id){
        temp.push(item);
      }else{
        if(item.children && item.children.length > 0){
           this.sonsTree(item.children,id,temp);
        }
      }
    }
     return temp;
   }
 
   //扁平化数据转树形结构
  transformTree (list) {
     const tree = []
     
     for (let i = 0, len = list.length; i < len; i++) {
         if (list[i].pId && list[i].rank == 3) {
             const item = this.queryChildren(list[i], list)
             
             tree.push(item)
         }
     }
     
     return tree
 }
 queryChildren (parent, list) {
  const children = []
  
  for (let i = 0, len = list.length; i < len; i++) {
      if (list[i].pId === parent.id) {
          const item = this.queryChildren(list[i], list)

          children.push(item)
      }
  }
  
  if (children.length) {
      parent.children = children
  }
  
  return parent
}
 //获取当前用户的权限范围
 getDepts(){
  const depts=JSON.parse(this.util.getStorage("depts"));
  console.log(depts)
  this.city=depts[0].city;//市
  this.province=depts[0].state;//省
  this.cities=depts;//区，街道，小区
  console.log(this.cities)
}
  constructor(
    private api: ApiService,
    private http: HttpClient,
    private msg: NzMessageService,
    private modalRef: NzModalRef,
    private util: UtilService,
    private ref: ChangeDetectorRef,
  ) { }

  async ngOnInit() {
   
    // if(this.isPartner){//是加盟商,角色只查询小区管理员
    //   await this.getRoleList().then(res => {
    //     this.schema.properties.role.enum = res.data.map(item => {
    //       return {label: item.roleName, value: item.id}
    //     })
    //   })
    //   this.schema.properties["userType"].ui["hidden"] = true
    //   this.sf.refreshSchema()
    // }else{//不是加盟商
    //   await this.getRoleList().then(res => {
    //     this.schema.properties.role.enum = res.data.map(item => {
    //       return {label: item.roleName, value: item.id}
    //     })
    //   })
    // }
   
    await this.getRoleList().then(res => {
      this.schema.properties.role.enum = res.data.map(item => {
        return {label: item.roleName, value: item.id}
      })
    })
    // await this.getPermitions().then(res => {
    //   this.schema.properties.dept.enum = res.data.map(item => {
    //     return {label: item.deptName, value: item.id}
    //   })
    // })
    // this.showForm = true;

      //440304
      this.getAreaTreeNode(0).then(res => {
        let arr=res.map(item =>{
          return {label:item.title,value:item.key}
        })
        if(this.util.getStorage('userAccount') != '"admin"'){
          arr=arr.filter(item => item.value == this.province);
        }
        this.schema.properties.state.enum = arr;
        this.ref.detectChanges();
        this.showForm=true;
      })
      this.getDepts()
  }
  ngAfterViewInit(): void {
    const roleArr = JSON.parse(this.util.getStorage("roles"))
    this.isPartner = roleArr.some(obj=>obj.roleId == "23f3b9b58f594c6eb18294941aa57fdf") //加盟商的角色id
    if(this.isPartner){//是加盟商
      this.schema.properties["userType"].ui["hidden"] = true
    }
  }
  

}
